package com.Final.hj;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Chatpage  extends AppCompatActivity implements View.OnClickListener{
    private static final int GET_MSG_LIST = 0;
    private static final int SEND_RECEIVE_MSG= 1;
    private String titleUname, toId, myId, flagId, hImgId, uname;
    private TextView chat_t_n;
    private Button chat_send_msg;
    private ImageView chat_p_back;
    private EditText chat_edit_text;
    private Socket socket;
    private List<ChatPageData> chat_page_msg_list = new ArrayList<ChatPageData>();
    private ListView chat_page_list;
    private ChatPageAdapter adapter;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_page);

        //初始化变量
        initView();

        //发送消息
        getPageMsg();
        //连接socket
        try {
            connect();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
        socket.disconnect();
    }
    //初始化变量
    public void initView(){
        chat_send_msg = (Button) findViewById(R.id.chat_send_msg);
        chat_t_n = (TextView) findViewById(R.id.chat_title_name);
        chat_p_back = (ImageView) findViewById(R.id.chat_page_back);
        chat_edit_text = (EditText) findViewById(R.id.chat_edit_text);
        chat_page_list = (ListView) findViewById(R.id.chat_page_list);

        chat_p_back.setOnClickListener(this);
        chat_send_msg.setOnClickListener(this);


        //这里获取 Intent的值
        Intent intent = this.getIntent();
        titleUname = intent.getStringExtra("titleUname");
        //id值
        toId= intent.getStringExtra("toId");
        flagId = intent.getStringExtra("flagId");
        uname = intent.getStringExtra("uname");
        hImgId = LoginSQLManger.getInstance(Chatpage.this).queryAll().gethImgId();
        myId= LoginSQLManger.getInstance(Chatpage.this).queryAll().getMyId();
        //设置标题
        chat_t_n.setText(intent.getStringExtra("titleUname"));
    }
    //链接socketio
    public void connect() throws URISyntaxException {
        socket = IO.socket("http://192.168.43.124:8080");
        socket.connect();
        //发送第一次保存对方id
        socket.emit("sConnection", toId);

        socket.on("readMsg", readMsg);
    }

    //获取信息列表
    public void getPageMsg(){

        //启动线程 发送请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/gchatmsg?flagId="+ flagId + "&id="+ LoginSQLManger.getInstance(Chatpage.this).queryAll().getMyId())
                            .build();

                    //这里发送异步请求即可
                    Call call = client.newCall(request);

                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure( Call call, IOException e) {
                            Log.i("TAG", e.toString());
                        }

                        @Override
                        public void onResponse( Call call, Response response) throws IOException {
                            String string = response.body().string();

                            //调用函数解析json
                            parseData(string);
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler(){
      @Override
      public void handleMessage(Message msg){
          switch (msg.what){
              case 0:
                  adapter = new ChatPageAdapter(Chatpage.this, chat_page_msg_list);
                  chat_page_list.setAdapter(adapter);
                  chat_page_list.setSelection(adapter.getCount() - 1);
                  break;
              case 1:
                  //这个必须ui线程调用
                  adapter.notifyDataSetChanged();
                  chat_page_list.setSelection(adapter.getCount() - 1);
                  break;
              default:
                  break;
          }
      }
    };

    public void parseData(String strJson) {
        //清空集合
//        chat_page_msg_list.clear();

        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(strJson).getAsJsonArray();
        Gson gson = new Gson();

        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            ChatPageData userBean = gson.fromJson(user, ChatPageData.class);
            chat_page_msg_list.add(userBean);
        }

        //首次更新
        handler.sendEmptyMessage(0);
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.chat_page_back:
                this.finish();
                break;
            case R.id.chat_send_msg:
                try {
                    sendMsg();
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
        }
    }

    public void sendMsg() throws Exception{

        String msg =  chat_edit_text.getText().toString().trim();
        if(msg.isEmpty()){
            return;
        }

        //获取当前的时间
        Date date=new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String msgTime = format.format(date);
        //发送对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("toId", toId);
        jsonObject.put("myId", myId);
        jsonObject.put("msg", msg);
        jsonObject.put("uname", uname);
        jsonObject.put("msgTime", msgTime);
        jsonObject.put("hImgId", hImgId);//此时头像应该是自己的

        //这里发送消息
        socket.emit("toOne", jsonObject);


        /*
            {
                isRead: '0',
                msg:'你和他已经称为好友了，快去和他聊天吧',
                msgId: '0',
                msgTime,
                hImgId: '0',
                uname: '车神-黄杰'
            }
         */

        ChatPageData chatMsgList = new ChatPageData("0", msg, myId, msgTime,
                hImgId, uname);

        //加入集合
        chat_page_msg_list.add(chatMsgList);
        adapter.notifyDataSetChanged();
        //清空文本框
        chat_edit_text.setText("");

        handler.sendEmptyMessage(1);
    }

    //监听socketio服务器返回的数据
    private Emitter.Listener readMsg = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
            JSONObject data = (JSONObject) args[0];
            try {
                String msg = data.getString("msg");
                String msgId = data.getString("msgId");
                String msgTime = data.getString("msgTime");
                String hImgId = data.getString("hImgId");
                String isRead = data.getString("isRead");
                String uname = data.getString("uname");
                ChatPageData chatMsgList = new ChatPageData(isRead, msg, msgId, msgTime,
                        hImgId, uname);
                //加入集合
                chat_page_msg_list.add(chatMsgList);

                //更新
                handler.sendEmptyMessage(1);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };
}
